<script>
export default {
  name:"inDepot",
  data() {
    let checkNumber =(rule,value,callback)=>{
      if(this.form.id){
        return callback();
      }
      this.$axios.post("/zzh-depot-head/findeByNumber?number="+this.form.number).then(res=>res.data).then(res=>{
        if(res.resultCode!=200){
          callback()
        }else{
          callback(new Error('单据编号已经存在'));
        }
      })
    };
    return {
      usersession:{},
      tableData: [],
      profucttableData:[],
      multipleSelection: [],
      ordertableData:[],
      orderSelection: [],
      tableDatatable: [
        { name: '', age: '' },
      ],
      hashMapUsers:{},
      hashMapDepots:{},
      hashMapOrganizations:{},
      pageNum:1,
      pageSize:5,
      total:5,
      pageNum1:1,
      pageSize1:5,
      total1:5,
      number:'',
      selectedOrganId:'',
      selectedDepotId:'',
      outerVisible:false,
      innerVisible: false,
      loading: true,
      isDisabledselectedOrganId: false,
      isDisabledlinkNumber: false,
      productform:{
        id:'',
        barCode:'',
        categoryId:'',
        name:'',
        model:'',
        standard:'',
        operNumber:'',
        color:'',
        unit:'',
        currentNumber:'',
      },
      form:{
        id:'',
        type:'',
        number:'',
        subType:'',
        createTime:'',
        operTime:'',
        organId:'',
        organName:'',
        creator:'',
        creatorName:'',
        accountId:'',
        changeAmount:'',
        backAmount:'',
        payType:'',
        remark:'',
        fileName:'',
        discount:'',
        discountMoney:'',
        discountLastMoney:'',
        status:'',
        source:'',
        linkNumber:'',
        deleteFlag:'',
        materialId:'',
        materialUnit:'',
        materialName:'',
        basicNumber:'',
        operNumber:'',
        unitPrice:'',
        allPrice:'',
        taxRate:'',
        taxMoney:'',
        taxLastMoney:'',
        productId:'',
        depotId:'',
        barCode:'',
        currentNumber:'',
      },
      rules: {
        createTime: [
          { required: true, message: '请选择日期时间', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请输入单据编号', trigger: 'blur' },
          {validator:checkNumber,trigger: 'blur'}
        ]
      }
    };
  },
  methods:{
    loadOption(){
      this.$axios.post('/zzh-depot-head/option',{
        type:"供应商",
        depot:"仓库"
      }).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.hashMapUsers = res.data.hashMapUsers;
          this.hashMapDepots = res.data.hashMapDepots;
        }else {
          alert('获取数据失败')
        }
      })
    },
    loadPost(){
      this.loading = true;
      this.$axios.post('/zzh-depot-head/list',{
        page:this.pageNum,
        limit:this.pageSize,
        number:this.number,
        type:"入库",
        subType:'其它',
      }).then(res=>res.data).then(res=>{
        this.loading = false;
        if(res.resultCode==200){
          this.tableData=res.data
          this.total=res.total
        }else {
          alert('获取数据失败')
        }
      })
    },
    //导出数据
    exportExcel() {
      //将响应数据类型设置为 Blob 对象   原因: 确保文件等二进制数据在传输过程中不会被转换或解析,对于文件下载非常有用，因为你可以直接将返回的二进制数据用于创建可下载的文件
      this.$axios.post('/zzh-excel/depotManageExcel',this.tableData, { responseType: 'blob' })
          .then(response => {
            // 将获取到的Excel数据转换为文件
            //Blob是二进制的容器，可以存放任意类型的二进制文件：图片/音频/文件
            //type : 类型设为Excel文件（.xlsx）的MIME类型，告诉浏览器创建的是一个Excel文件，默认使用excel打开
            const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

            // 创建隐藏的下载链接并模拟点击下载
            const link = document.createElement('a');
            //创建一个可供用户下载的链接
            link.href = URL.createObjectURL(blob);
            link.download = '其它入库信息表格.xlsx';
            //设置链接的打开方式为新标签页（_blank），这样用户点击链接后会在新标签页中下载文件
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          })
          .catch(error => {
            console.error(error);
          });
    },
    add(){
      this.outerVisible=true
      this.$nextTick(()=>{
        this.resetForm()
      })
    },
    loadAdd(){
      //表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          if(this.form.id){
            this.doUpdate();
            this.form.id='';
          }else {
            this.doAdd()
          }
        } else {
          return false;
        }
      });
    },
    doAdd(){
      if(this.selectedDepotId===null || this.selectedDepotId===""){
        this.$message({
          showClose: true,
          message: '仓库不能为空',
          type: 'error'
        });
      }else if(this.form.materialId===null || this.form.materialId===""){
        this.$message({
          showClose: true,
          message: '请选择商品',
          type: 'error'
        });
      }else if(this.form.operNumber===null || this.form.operNumber===""){
        this.$message({
          showClose: true,
          message: '请输入商品数量',
          type: 'error'
        });
      }
      else {
        this.form.type="入库";
        this.form.subType="其它";
        this.$axios.post('/zzh-depot-head/add',this.form).then(res=>res.data).then(res=>{
          if(res.resultCode==200){
            this.outerVisible=false
            this.$message({
              showClose: true,
              message: '新增数据成功',
              type: 'success'
            });
            this.loadPost()
          }else {
            this.$message({
              showClose: true,
              message: res.message,
              type: 'error'
            });
          }
        })
      }
    },
    mod(row){
      if(row.status=='0'){
        this.outerVisible=true
        this.$nextTick(()=>{
          this.form.id=row.id
          this.form.organId=row.organId
          this.form.createTime=row.createTime
          this.form.number=row.number
          this.form.productId=row.productId
          this.form.materialName=row.materialName
          this.form.materialUnit=row.materialUnit
          this.form.operNumber=row.operNumber
          this.form.unitPrice=row.unitPrice
          this.form.allPrice=row.allPrice
          this.form.taxRate=row.taxRate
          this.form.taxMoney=row.taxMoney
          this.form.taxLastMoney=row.taxLastMoney
          this.form.remark=row.remark
          this.form.discount=row.discount
          this.form.discountMoney=row.discountMoney
          this.form.discountLastMoney=row.discountLastMoney
          this.form.materialId=row.materialId
          this.form.linkNumber=row.linkNumber
          this.form.depotId=row.depotId
          this.form.productId=row.barCode
          this.form.currentNumber=row.currentNumber
          // 遍历hashMapDepots，找到匹配的 key:id,this.hashMapDepots[key]值
          for (let key in this.hashMapDepots) {
            if (parseInt(key) === this.form.depotId) {
              this.selectedDepotId = this.hashMapDepots[key]; // 将 key 设置为选中值
              break;
            }
          }
          // 遍历 hashMapUsers，找到匹配的 key:id,this.hashMapUsers[key]值
          for (let key in this.hashMapUsers) {
            if (parseInt(key) === this.form.organId) {
              this.selectedOrganId = this.hashMapUsers[key]; // 将 key 设置为选中值
              break;
            }
          }
          //初始化表单
          this.tableDatatable=[
            {}
          ]
        })
      }else {
        this.$message({
          showClose: true,
          message: '抱歉，只有未审核的单据才能修改',
          type: 'error'
        });
      }
    },
    handleSelectChange(){
      this.form.organId = this.selectedOrganId;
    },
    handleSelectDepotIdChange(){
      this.form.depotId = this.selectedDepotId;
      // 遍历 hashMapUsers，找到匹配的 key:id,this.hashMapUsers[key]值
      for (let key in this.hashMapDepots) {
        if (key === this.selectedDepotId) {
          this.selectedDepotId = this.hashMapDepots[key]; // 将 key 设置为选中值
          break;
        }
      }
      //初始化表单
      this.tableDatatable=[
        {}
      ]
    },
    doUpdate(){
      this.form.type="入库";
      this.form.subType="其它";
      this.$axios.put('/zzh-depot-head/update',this.form).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.outerVisible=false
          this.$message({
            showClose: true,
            message: '更新数据成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: res.message,
            type: 'error'
          });
        }
      })
    },
    del(id){
      this.$axios.delete('/zzh-depot-head/delete?id='+id).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
          this.loadPost()
        }else {
          this.$message({
            showClose: true,
            message: '删除失败',
            type: 'error'
          });
        }
      })
    },
    updateStatus(row){
      if(row.status=='0'){
        console.log(row)
        this.$axios.put('/zzh-depot-head/updateStatus',{
          id:row.id,
          materialId:row.materialId,
          type:row.type,
          operNumber:row.operNumber,
          depotId:row.depotId
        }).then(res=>res.data).then(res=>{
          if(res.resultCode==200){
            this.$message({
              showClose: true,
              message: '审核成功',
              type: 'success'
            });
            this.loadPost()
          }else {
            this.$message({
              showClose: true,
              message: res.message,
              type: 'error'
            });
          }
        })
      }else {
        this.$message({
          showClose: true,
          message: '抱歉，只有未审核的单据才能审核',
          type: 'error'
        });
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum=1
      this.pageSize=val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum=val
      this.loadPost()
    },
    handleSizeChange1(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum1=1
      this.pageSize1=val
      this.loadPost()
    },
    handleCurrentChange1(val) {
      console.log(`当前页: ${val}`);
      this.pageNum1=val
      this.$axios.post('/zzh-product/list',{
        page:this.pageNum1,
        limit:this.pageSize1,
      }).then(res=>res.data).then(res=>{
        if(res.resultCode==200){
          this.profucttableData=res.data
          this.total1=res.total1
        }else {
          alert('获取数据失败')
        }
      })
    },
    resetParam(){
      this.number=''
      this.loadPost()
    },
    resetForm() {
      this.isDisabledselectedOrganId= false;
      this.isDisabledlinkNumber= false;
      this.form.depotId='';
      this.selectedDepotId='';
      this.form.productId='';
      this.form.materialName='';
      this.form.materialId='';
      this.form.materialUnit='';
      this.form.operNumber='';
      this.form.unitPrice='';
      this.form.allPrice='';
      this.form.taxRate='';
      this.form.taxMoney='';
      this.form.taxLastMoney='';
      this.form.organId='';
      this.selectedOrganId='';
      this.form.currentNumber='';
      //重置窗体
      this.$refs.form.resetFields();
    },
    select(){
      this.innerVisible=true
      this.loading = true
      this.$axios.post('/zzh-product/list',{
        page:this.pageNum1,
        limit:this.pageSize1,
      }).then(res=>res.data).then(res=>{
        this.loading = false
        if(res.resultCode==200){
          this.profucttableData=res.data
          this.total1=res.total1
        }else {
          alert('获取数据失败')
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    copyProduct(){
      this.form.productId=this.multipleSelection[0].barCode
      this.form.materialId=this.multipleSelection[0].id;
      this.form.materialName=this.multipleSelection[0].name
      this.form.materialUnit=this.multipleSelection[0].unit
      this.form.unitPrice=this.multipleSelection[0].purchaseDecimal
      this.form.currentNumber=this.multipleSelection[0].currentNumber
      this.innerVisible=false
      this.tableDatatable=[
        {}
      ]
    },
  },
  beforeMount() {
    this.loadOption();
    this.loadPost();
    this.usersession = JSON.parse(sessionStorage.getItem('user'));
  },
  watch: {
    'form.operNumber'(newVal) {
      this.form.allPrice = newVal * this.form.unitPrice;
    },
    'form.unitPrice'(newVal) {
      this.form.allPrice = this.form.operNumber * newVal;
    },
  }
}
</script>

<template>
  <div>
    <!--    按钮-->
    <div style="margin-bottom: 5px">
      <el-input v-model="number" placeholder="请输入单据编号" suffix-icon="el-icon-search" style="width: 200px"
                @keyup.enter.native="loadPost"></el-input>
      <el-button type="primary" style="margin-left: 5px" @click="loadPost">查询</el-button>
      <el-button type="success" @click="resetParam">重置</el-button>
      <el-button type="primary" style="margin-left: 5px" @click="add">新增</el-button>
      <el-button type="success" plain @click="exportExcel" style="margin-left: 10px" icon="el-icon-download">导出Excel</el-button>
    </div>

    <!--    表单-->
    <el-table :data="tableData" v-loading="loading"
              :header-cell-style="{background:'#f3f6fd',color:'#555'}">

      <el-table-column prop="operate" label="操作"  width="200">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm
              title="确定删除吗？"
              style="margin-left: 5px;margin-right: 5px"
              @confirm="del(scope.row.id)"
          >
            <el-button slot="reference" size="small" type="danger" >删除</el-button>
          </el-popconfirm>
          <el-button size="small" type="success" v-if="usersession.position === '1' " @click="updateStatus(scope.row)" >审核</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-tag
              :type="scope.row.status === '1' ? 'success' : 'danger'"
              disable-transitions>{{scope.row.status === '1' ? '已审核' : scope.row.status === '2' ? '完成入库' : scope.row.status === '9' ? "审核中" : "未审核"}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="organName" label="供应商" width="140">
      </el-table-column>
      <el-table-column prop="number" label="单据编号" width="200">
      </el-table-column>
      <el-table-column prop="materialName" label="商品信息" width="120">
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="200">
      </el-table-column>
      <el-table-column prop="creatorName" label="操作员" width="120">
      </el-table-column>
      <el-table-column prop="operNumber" label="数量" width="120">
      </el-table-column>
      <el-table-column prop="unitPrice" label="单价" width="120">
      </el-table-column>
      <el-table-column prop="allPrice" label="合计金额" width="120">
      </el-table-column>

    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <!--    外提示框-->
    <el-dialog
        title="提 示"
        :visible.sync="outerVisible"
        width="80%"
    >
      <el-form ref="form" :model="form" label-width="100px" size="mini" :rules="rules">

        <el-row>

          <el-col :span="5">
            <el-form-item label="供应商:" prop="selectedOrganId">
              <el-select v-model="selectedOrganId" @change="handleSelectChange" filterable placeholder="选择供应商" :disabled="isDisabledselectedOrganId">
                <el-option
                    v-for="(key,value) in hashMapUsers"
                    :key="value"
                    :label="key"
                    :value="value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="单据日期:" prop="createTime">
              <el-date-picker
                  v-model="form.createTime"
                  type="datetime"
                  placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="6" style="margin-left: 120px;">
            <el-form-item label="单据编号:" prop="number">
              <el-input v-model="form.number" placeholder="单据编号例如：QTRU1001" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-table :data="tableDatatable" ref="table">
          <el-table-column prop="selectedDepotId" label="仓库名称:"  width="150">
            <el-select v-model="selectedDepotId" @change="handleSelectDepotIdChange" filterable placeholder="选择仓库" size="mini">
              <el-option
                  v-for="(key,value) in hashMapDepots"
                  :key="value"
                  :label="key"
                  :value="value">
              </el-option>
            </el-select>
          </el-table-column>
          <el-table-column prop="productId" label="条码"  width="150">
            <el-input v-model="form.productId" size="mini" @keyup.enter.native="select()">
              <el-button slot="append" icon="el-icon-search" @click="select()"></el-button>
            </el-input>
          </el-table-column>
          <el-table-column prop="materialName" label="名称">
            <el-input v-model="form.materialName" :disabled="true"  size="mini"></el-input>
          </el-table-column>
          <el-table-column prop="currentNumber" label="库存">
            <el-input v-model.number="form.currentNumber" type="number" :disabled="true" size="mini"></el-input>
          </el-table-column>

          <el-table-column prop="operNumber" label="数量" >
            <template slot-scope="scope">
              <el-input v-model.number="form.operNumber"  type="number" size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="单价">
            <template slot-scope="scope">
              <el-input v-model.number="form.unitPrice"  type="number" size="mini"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="allPrice" label="金额">
            <template slot-scope="scope">
              <el-input v-model.number="form.allPrice" type="number" size="mini" disabled></el-input>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item label="备注" prop="remark">
          <el-input
              type="textarea"
              placeholder="请输入备注"
              v-model="form.remark"
              maxlength="30"
              show-word-limit
              size="mini"
          >
          </el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="outerVisible = false">取 消</el-button>
        <el-button type="primary" @click="loadAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!--    商品表单提示框-->
    <el-dialog
        title="选择商品"
        :visible.sync="innerVisible"
        width="60%"
    >
      <!--    商品表单-->
      <el-table :data="profucttableData" v-loading="loading"
                ref="multipleTable"
                :header-cell-style="{background:'#f3f6fd',color:'#555'}"
                @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column prop="barCode" label="条码" width="140">
        </el-table-column>
        <el-table-column prop="name" label="名称" width="140">
        </el-table-column>
        <el-table-column prop="standard" label="规格" width="120">
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="120">
        </el-table-column>
        <el-table-column prop="categoryId" label="类别" width="120">
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="120">
        </el-table-column>
        <el-table-column prop="currentNumber" label="库存" width="120">
        </el-table-column>
      </el-table>

      <!--    分页-->
      <el-pagination
          @size-change="handleSizeChange1"
          @current-change="handleCurrentChange1"
          :current-page="pageNum1"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize1"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total1">
      </el-pagination>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerVisible = false">取 消</el-button>
        <el-button type="primary" @click="copyProduct">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<style scoped>

</style>